package org.meetunexpectedly.holder;

import javax.servlet.http.HttpServletRequest;

/**
 * @Description: 请求ip共享变量缓存
 * @Author: pupil
 * @Date: 2024/09/13 下午 7:58
 */
public class IPHolder {

    private static ThreadLocal<String> userThreadLocal = new ThreadLocal<>();

    // 添加
    public static void set(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            // 如果没有X-Forwarded-For头部或者值为空/unknown，则使用直接连接的IP
            ip = request.getRemoteAddr();
        } else {
            // 如果X-Forwarded-For存在，则取第一个IP（通常是客户端IP）
            ip = ip.split(",")[0].trim();
        }
        userThreadLocal.set(ip);
    }

    // 获取
    public static String get() {
        return userThreadLocal.get();
    }

    // 删除
    public static void clear() {
        userThreadLocal.remove();
    }
}
